<template>
  <div class="app-container">
    <template v-if="!showDetailIndex">
    <div class="search-container">
      <el-form ref="form" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="科研项目名称">
          <el-input
            v-model="queryParams.keywords"
            placeholder="科研项目名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="el-icon-search">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <el-button type="success" @click="openDialog()"
          ><i class="el-icon-circle-plus"></i> 新增</el-button>
        <el-button type="success" @click="openImportDialog()"
          ><i class="el-icon-circle-plus"></i> 更新样本数据</el-button>
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
          ><i class="el-icon-delete"></i> 删除</el-button>
      </template>

      <el-table
        v-loading="loading"
        :data="dataList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" width="55" prop="dataIndex"/>
        <el-table-column label="项目名称" prop="name"/>
        <el-table-column label="项目名称（英文）" prop="enName" width="220"/>
        <el-table-column label="项目状态" prop="statusText"/>
        <el-table-column label="简述" prop="describe"/>
        <el-table-column label="创建时间" prop="createTimeText"/>
        <el-table-column label="更新时间" prop="updateTimeText"/>
        <el-table-column fixed="right" label="操作"  min-width="300" width="365">
          <template #default="scope">
            <el-button type="primary" size="small" link @click="openDetailDialog(scope.row)"><i class="el-icon-view"></i> 查看</el-button>
            <el-button type="info" size="small" link @click="openAuthDialog(scope.row.id)"><i class="el-icon-edit"></i> 配置权限</el-button>
            <el-button type="warning" size="small" link @click="openDialog(scope.row.id)" :disabled="scope.row.sourceType == 'SYS_BUILD'"><i class="el-icon-edit"></i> 编辑</el-button>
            <el-button type="danger" size="small" link @click="handleDelete(scope.row.id)" :disabled="scope.row.sourceType == 'SYS_BUILD'"><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 表单弹窗 -->
    <el-dialog
      :visible.sync="dialog.visible"
      :title="dialog.title"
      width="800px"
      :before-close="closeDialog"
    >
      <el-form
        ref="projectFormRef"
        :model="formData"
        :rules="rules"
        label-width="180px"
      >
        <el-form-item label="科研项目名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入科研项目名称" />
        </el-form-item>
        <!-- <el-form-item label="科研项目名称（英文）" prop="enName">
          <el-input v-model="formData.enName" placeholder="请输入科研项目名称（英文）" />
        </el-form-item> -->
        <el-form-item label="ncbiId" prop="ncbiId">
          <el-input v-model="formData.ncbiId" placeholder="请输入ncbiId" />
        </el-form-item>
        <el-form-item label="科研项目负责人" prop="principal">
          <el-input v-model="formData.principal" placeholder="请输入科研项目负责人" />
        </el-form-item>
        <el-form-item label="项目类型" prop="type">
          <el-select v-model="formData.type">
            <el-option label="科研项目" value="SCIENTIFIC_RESEARCH"></el-option>
            <el-option label="公共项目" value="PUBLICATION"></el-option>
            <el-option label="微生态检测项目" value="REPORT"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目状态" prop="status">
          <el-select v-model="formData.status">
            <el-option label="未开始" value="NOT_START"></el-option>
            <el-option label="进行中" value="IN_PROGRESS"></el-option>
            <el-option label="已完成" value="COMPLETED"></el-option>
            <el-option label="已终止" value="TERMINATED"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="简述" prop="describe">
          <el-input v-model="formData.describe" type="textarea" :autosize="{ minRows: 8}" placeholder="请输入简述" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addOrUpdate">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      :visible.sync="uploadSampleDialog.visible"
      :title="uploadSampleDialog.title"
      width="800px"
      :before-close="closeUploadSampleDialog">
      <el-form ref="uploadSampleFormRef" :model="uploadSampleForm" label-width="130px">
        <el-form-item label="FastQ 文件基路径" prop="fastqBasePath">
          <el-input v-model="uploadSampleForm.fastqBasePath"  placeholder="请输入FastQ 文件基路径" />
        </el-form-item>
        <el-form-item label="物种" prop="species">
          <el-select v-model="uploadSampleForm.species" placeholder="请选择物种">
            <el-option label="人类" value="human"></el-option>
            <el-option label="大鼠" value="mouse"></el-option>
            <el-option label="小鼠" value="rat"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实验策略" prop="strategy">
          <el-select v-model="uploadSampleForm.strategy" placeholder="请选择实验策略">
            <el-option label="Amplicon" value="Amplicon"></el-option>
            <el-option label="Metagenomics" value="Metagenomics"></el-option>
            <el-option label="WES" value="WES"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="测序方式" prop="layout">
          <el-select v-model="uploadSampleForm.layout" placeholder="请选择测序方式">
            <el-option label="单端测序" value="SINGLE"></el-option>
            <el-option label="双端测序" value="PAIRED"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件内容" prop="content">
          <el-input v-model="uploadSampleForm.content" type="textarea" :autosize="{ minRows: 10, maxRows: 50}" placeholder="请输入文件内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="uploadSample">导入样本</el-button>
          <el-button @click="closeUploadSampleDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      :visible.sync="importSampleDialog.visible"
      :title="importSampleDialog.title"
      width="800px"
      :before-close="closeImportSampleDialog">
      <el-form ref="importSampleFormRef" :model="importSampleFormData" label-width="130px">
        <el-form-item label="FastQ 文件基路径" prop="fastqBasePath">
          <el-input v-model="importSampleFormData.fastqBasePath"  placeholder="请输入FastQ 文件基路径" />
        </el-form-item>
        <!-- <el-form-item label="物种" prop="species">
          <el-select v-model="importSampleFormData.species" placeholder="请选择物种">
            <el-option label="人类" value="human"></el-option>
            <el-option label="大鼠" value="mouse"></el-option>
            <el-option label="小鼠" value="rat"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实验策略" prop="strategy">
          <el-select v-model="importSampleFormData.strategy" placeholder="请选择实验策略">
            <el-option label="Amplicon" value="Amplicon"></el-option>
            <el-option label="Metagenomics" value="Metagenomics"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="测序方式" prop="layout">
          <el-select v-model="importSampleFormData.layout" placeholder="请选择测序方式">
            <el-option label="单端测序" value="SINGLE"></el-option>
            <el-option label="双端测序" value="PAIRED"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="文件内容" prop="content">
          <el-input v-model="importSampleFormData.content" type="textarea" :autosize="{ minRows: 10, maxRows: 50}" placeholder="请输入文件内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="importUpdateSample">更新样本</el-button>
          <el-button @click="closeImportSampleDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :visible.sync="authDialog.visible" :title="authDialog.title" width="800px" :before-close="closeAuthDialog" :close-on-click-modal="false">
      <el-button type="success" @click="openAddAuthDialog()"><i class="el-icon-circle-plus"></i> 新增</el-button>
      <el-table v-loading="loading" :data="projectAuthDataList" highlight-current-row border style="height: 500px; margin-top: 8px;">
        <el-table-column label="序号" width="55" prop="dataIndex"/>
        <el-table-column label="权限类型" prop="authTypeText"/>
        <el-table-column label="权限对象名称" prop="authName"/>
        <el-table-column label="创建时间" prop="createTimeText"/>
        <el-table-column fixed="right" label="操作"  min-width="120" width="120">
          <template #default="scope">
            <el-button type="danger" size="small" link @click="handleProjectAuthDelete(scope.row.id)"><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog :visible.sync="addAuthDialog.visible" :title="addAuthDialog.title" width="300px" :before-close="closeAddAuthDialog" :close-on-click-modal="false">
      <el-form ref="ref01" :model="addAuthForm" label-width="80px">
        <el-form-item label="权限类型" prop="authType">
          <el-select v-model="addAuthForm.authType" placeholder="请选择权限类型" @change="changeAuthType">
            <el-option label="角色" value="ROLE"></el-option>
            <el-option label="人员" value="USER"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="授权对象" prop="authId">
          <el-select v-model="addAuthForm.authId"  placeholder="请选择授权对象">
            <el-option v-for="item in authObjList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addAuth">新增授权</el-button>
          <el-button @click="closeAddAuthDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    </template>

    <projectDetailIndex :checkedProject="checkedProject" v-if="showDetailIndex" @close="close"></projectDetailIndex>

  </div>
</template>

<script>

import seqSampleApi from '@/api/sequence/seqSample'
import projectDetailIndex from '@/views/sequence/project/detail'
import seqProjectApi from '@/api/sequence/project'
import userApi from '@/api/system/user'
import roleApi from '@/api/system/role'
import seqProjectAuthApi from '@/api/sequence/seqProjectAuth'


import { formatDate } from '@/utils/formatTime'
export default {
	name: 'dictIndex',
  components: {
    projectDetailIndex,
  },
	data() {
		return {
			queryParams: {
        keywords: '',
        pageNum: 0,
        pageSize: 10,

      },
      total: 0,
      loading: false,
      dataList: [],
      ids: [],
      dialog: {},
      formData: {},
      rules: {
        name: [{ required: true, message: '请输入科研项目名称', trigger: 'blur' }],
        enName: [{ required: true, message: '请输入科研项目名称（英文）', trigger: 'blur' }],
        // ncbiId: [{ required: true, message: '请输入ncbiId', trigger: 'blur' }],
        // principal: [{ required: true, message: '请输入科研项目负责人', trigger: 'blur' }],
        type: [{ required: true, message: '请选择项目类型', trigger: 'change' }],
      },

      showDetailIndex: false,
      checkedProject: {},

      importSampleDialog: {},
      importSampleFormData: {},

      uploadSampleDialog: {},
      uploadSampleForm: {},

      statusMap: {
        NOT_START: '未开始',
        IN_PROGRESS: '进行中',
        COMPLETED: '已完成',
        TERMINATED: '已终止',
      },

      authDialog: {},
      addAuthDialog: {},
      projectAuthDataList: [],
      checkedId: -1,
      addAuthForm: {},
      authObjList: [],

		};
	},
  methods: {
    changeAuthType (r) {
      switch (r) {
        case 'USER':
          userApi.list().then(res => {
            this.authObjList = res.data;
          })
          break;
        case 'ROLE':
          roleApi.list().then(res => {
            res.data.forEach(v => {
              v.name = v.zhCnName
            })
            this.authObjList = res.data;
          })
          break;
      }
    },
    addAuth () {
      this.addAuthForm.projectId = this.checkedId;
      seqProjectAuthApi.add(this.addAuthForm).then(res => {
        this.$message({message: '授权新增成功！', type: 'success'});
        this.closeAddAuthDialog();
        seqProjectAuthApi.list(this.checkedId).then(res => {
          let index = 1;
          res.data.forEach((v) => {
            v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
            v.authTypeText = v.authType == 'USER' ? '人员' : '角色'
            v.dataIndex = index++;
          });
          this.projectAuthDataList = res.data;
        })
      })
    },
    openAddAuthDialog () {
      this.$set(this.addAuthDialog, 'visible', true);
      this.$set(this.addAuthDialog, 'title', '新增权限');
    },
    closeAddAuthDialog () {
      this.$set(this.addAuthDialog, 'visible', false);
    },
    handleProjectAuthDelete (id) {
      seqProjectAuthApi.delete(id).then(res => {
        this.$message({message: '授权信息删除成功！', type: 'success'});
        seqProjectAuthApi.list(this.checkedId).then(res => {
          let index = 1;
          res.data.forEach((v) => {
            v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
            v.authTypeText = v.authType == 'USER' ? '人员' : '角色'
            v.dataIndex = index++;
          });
          this.projectAuthDataList = res.data;
        })
      })
    },
    openAuthDialog (id) {
      this.$set(this.authDialog, 'visible', true);
      this.$set(this.authDialog, 'title', '配置权限');
      this.checkedId = id;
      seqProjectAuthApi.list(id).then(res => {
        let index = 1;
        res.data.forEach((v) => {
          v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
          v.authTypeText = v.authType == 'USER' ? '人员' : '角色'
          v.dataIndex = index++;
        });
        this.projectAuthDataList = res.data;
      })
    },
    closeAuthDialog () {
      this.$set(this.authDialog, 'visible', false);
    },
    importUpdateSample () {
      seqSampleApi.labUploadContent(this.importSampleFormData).then(res => {
        if (res.data.length != 0) {
          let names = [];
          res.data.forEach(v => {
            names.push(v.name)
          })
          this.$message.error('样本【'+ names.join(',') +'】不存在！');
          return;
        }
        this.$message({message: '样本数据更新完成！', type: 'success'});
        this.$set(this.importSampleDialog, 'visible', false);
      })
    },
    uploadSample () {
      seqSampleApi.uploadResearchSample(this.uploadSampleForm).then(res => {
        this.$message({message: '样本数据解析完成！', type: 'success'});
        this.$set(this.uploadSampleDialog, 'visible', false);
      })
    },
    closeUploadSampleDialog () {
      this.$set(this.uploadSampleDialog, 'visible', false);
    },
    closeImportSampleDialog () {
      this.$set(this.importSampleDialog, 'visible', false);
    },
    openUploadSampleDialog () {
      this.$set(this.uploadSampleDialog, 'visible', true);
      this.$set(this.uploadSampleDialog, 'title', '导入样本');
    },

    openImportDialog () {
      this.$set(this.importSampleDialog, 'visible', true);
      this.$set(this.importSampleDialog, 'title', '更新样本');
    },
    close () {
      this.showDetailIndex = false;
    },
    openDetailDialog (row) {
      this.showDetailIndex = true;
      this.checkedProject = row;
    },
    closeDetailDialog () {
      this.detailDialgVisbile = false;
    },
    handleQuery() {
      this.loading = true;
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize
      };
      seqProjectApi.page(params).then((res) => {
        let data = res.data;
        let that = this;
        let index = 1
        data.content.forEach((v) => {
          v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
          v.updateTimeText = formatDate(new Date(v.updateTime), "YYYY-mm-dd HH:MM:SS")
          v.statusText = that.statusMap[v.status]
          v.dataIndex = index++;
        });
        this.dataList = data.content;
        
        this.total = data.count;
        this.loading = false;
      }).catch(() => {});
    },
    resetQuery() {
      this.queryParams = {
        keywords: '',
        pageNum: 0,
        pageSize: 10,
      };
      this.handleQuery();
    },
    
    addOrUpdate() {
      let that = this;
      this.$refs['projectFormRef'].validate((valid) => {
        if (!valid) {
          this.$message.error('必填字段未填写！');
          return false;
        } else {
          if (this.formData.id) {
            seqProjectApi.update(this.formData).then((res) => {
              this.$message({message: '科研项目更新成功！', type: 'success'});
              that.closeDialog();
            });
          } else {
            seqProjectApi.add(this.formData).then((res) => {
              this.$message({message: '科研项目添加成功！', type: 'success'});
              that.closeDialog();
              that.uploadSampleForm.projectId = res.data.id;
              that.openUploadSampleDialog();
            });
          }
        }
      });
      
    },
    openDialog(id) {
      this.$set(this.dialog, 'visible', true);
      let that = this;
      if (id) {
        this.$set(this.dialog, 'title', '编辑科研项目');
        seqProjectApi.get(id).then((res) => {
          let data = res.data;
          that.formData = data;

        });
      } else {
        this.$set(this.dialog, 'title', '新增科研项目');
        that.formData = {};
      }

    },
    closeDialog() {
      this.$set(this.dialog, 'visible', false);
      this.$set(this.dialog, 'title', '');
      this.$refs['projectFormRef'].resetFields();
      this.handleQuery();
    },
    handleDelete(id) {
      if (id) {
        this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          seqProjectApi.delete(id).then((res) => {
            this.$message({message: '科研项目删除成功！', type: 'success'});
            this.handleQuery();
          });
        }).catch(() => {});
      } else {
        this.$message.error('暂不支持批量删除科研项目！');
      }
    },
    handleSelectionChange(val) {
      this.ids = [];
      val.forEach(v => {
        this.ids.push(v.id);
      });
    },
    handleSelectionRoleChange(rows) {
      if (rows) {
        let arr = [];
        rows.forEach((v) => {
          arr.push(v.id);
        });
        this.selectRoleIdArr = arr;
      }
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.handleQuery();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.handleQuery();
    },
  },
  created() {
    this.handleQuery();
  }
};
</script>

<style scoped>
.el-pagination {
  margin-top: 10px;
  float: right;
  margin-bottom: 10px;
}
</style>